package tv_model;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class Communication extends Thread {
	
	private static webSocket ws;
	private static Tv tv;
	private static boolean steelAlive;
	private static String testConnection = "";
	
	public Communication(webSocket ws, Tv tv){
		Communication.ws = ws;
		Communication.tv = tv;
		Communication.steelAlive = true;
	}
	
    private void handleConnection() throws InterruptedException {
    	try{ 
	    	String message = ws.getMessage();
	    	System.out.println("Message: "+message+".");//TODO afficher sur Emulator_tv
	    	
	    	if(message.equals("GET")){
	    		ws.sendMessage(Communication.tv.toJSON());
	    	}else{
				ws.close();
	    	}
	    	
	    	SteelAliveThread sAlive = new SteelAliveThread();
	    	sAlive.start();
	    	
	    	int delay = 60000;   	// delay for 1 min.
	    	int period = 180000;    // repeat every 3 min.
	    	
	    	Timer timer = new Timer();
	    	
	    	timer.scheduleAtFixedRate(new TimerTask() {
	    		public void run() {
	    			if(testConnection == null){
	    				steelAlive = false;
	    			}else{
	    				testConnection = null;
	    			}
	    		}
	    	}, delay, period);
	    	
	    	while(steelAlive){
	    		Thread.sleep(1000);
	    		ws.sendMessage(Communication.tv.toJSON());
	    	}
	    	timer.cancel();
	    	sAlive.join();
	    	if(!ws.isClosed())
	    		ws.close();
	    	
    	}catch(IOException e){
    		steelAlive = false;
    		if(!ws.isClosed())
    			ws.close();
    	}
    	
    }
	
    public void run() {
    	try {
			handleConnection();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    }
    
	static public class SteelAliveThread extends Thread {
		@Override
		public void run() {
			while(steelAlive){
				try{
					testConnection = ws.getMessage();
					if(testConnection.equals(Constants.PLUS_CHANNEL)){
						Communication.tv.changeChannel(Constants.Operation.PLUS);
					}else if(testConnection.equals(Constants.MINUS_CHANNEL)){
						Communication.tv.changeChannel(Constants.Operation.MINUS);
					}else if (testConnection==null){
						steelAlive = false;
					}
				}catch(IOException e){
					steelAlive = false;
					ws.close();
				}
			}
		}
	}  

}
